<?php
/**
 * @link https://gitee.com/toshcn/yii2-oauth2-server
 * @copyright Copyright (c) 2018 len168.com
 * @license https://gitee.com/toshcn/yii2-oauth2-server/blob/master/LICENSE
 */

namespace toshcn\yii2\oauth2server\controllers;

use Yii;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\Request;

/**
 * Token controller for the `oauth2server` module
 */
class AuthorizeController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return parent::behaviors();
    }

    /**
     * @return mixed
     */
    public function actionIndex()
    {
        $server = $this->module->getServer();
        if (Yii::$app->getUser()->getIsGuest()) {
            $redirectUrl = Url::to(['/oauth2/authorize'], true) . http_build_query($this->module->getRequest()->getQueryParams());

            return $this->redirect(Url::to($this->module->loginAction, true) . '?redirect_url=' . urlencode($redirectUrl));
        }

        $clientId = $this->module->getRequest()->get('client_id');
        $state = $this->module->getRequest()->get('state');
        $client = $server->getStorage('client_credentials')->getClientDetails($clientId);

        $response = $server->handleAuthorizeRequest(null, null, true, $server->getStorage('user_credentials')->getId());
        $code = (int) $response->getStatusCode();
        $parameters = $response->getParameters();

        if (isset($parameters['error']) && $parameters['error']) {
            $url = urldecode($client['redirect_uri']) . "?code={$code}&state={$state}&error={$parameters['error']}&error_message=" . $this->module->t('common', $parameters['error_description']);

            return $this->redirect($url);
        } else {

            return $this->redirect($response->getHttpHeaders()['Location']);
        }
    }

    public function actionLogin()
    {
        return $this->render('login');
    }
}
